package flextv.main.command {

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import flash.filesystem.File;

import flextv.core.logic.Logger;
import flextv.core.vo.Playlist;
import flextv.core.vo.StoredItem;
import flextv.main.logic.AirUtil;
import flextv.main.logic.MainServices;
import flextv.search.event.AddSearchItemEvent;
import flextv.search.logic.SearchModel;
import flextv.search.vo.SearchItem;

import mx.logging.ILogger;

public class AddSearchItemCommand implements ICommand {
	
	private static const LOG: ILogger = Logger.getLog(AddSearchItemCommand);
	
	public function AddSearchItemCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: AddSearchItemEvent = _event as AddSearchItemEvent;
		LOG.info("Executing [event=" + event + "].");
		
		const targetPlaylist: Playlist = event.targetPlaylist;
		const searchItem: SearchItem = event.searchItem;
		
		const newStoredItem: StoredItem = new StoredItem(
			searchItem.yid,
			searchItem.title,
			searchItem.duration,
			searchItem.fileUri // could be set (if was already viewed), or null
		);
		// not necessary ... newStoredItem.playlistId = targetPlaylist.id;
		
		const targetFile: File = AirUtil.resolveFlvFile(newStoredItem.yid);
		
		MainServices.instance.downloadService.download(newStoredItem, targetFile, function(): void {
			
			newStoredItem.fileUri = "file://" + AirUtil.resolveFlvFile(newStoredItem.yid).nativePath.replace(/\\/,"/") // convert DOS \ to UNIX /
			MainServices.instance.persistenceService.insertStoredItem(newStoredItem, targetPlaylist);
			
			targetPlaylist.storedItems.addItem(newStoredItem);
			
			const searchItemIndex: int = SearchModel.instance.searchItems.getItemIndex(searchItem);
			SearchModel.instance.searchItems.removeItemAt(searchItemIndex);
		});
	}
	
}
}